/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.bincent.common.web.response;

import com.bincent.common.web.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * description
 *
 * @author Matrix
 * @date 2020-07-08 17:08
 * @since 0.1.0
 */
@RestControllerAdvice
public class CommonResponseAdvice implements ResponseBodyAdvice<Object> {

	private static final Logger log = LoggerFactory.getLogger(CommonResponseAdvice.class);

	@Override
	public boolean supports(MethodParameter returnType,
	                        Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType,
	                              MediaType selectedContentType, Class<?
			extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
	                              ServerHttpResponse response) {
		if (selectedContentType.toString().contains(MediaType.APPLICATION_JSON_VALUE)) {
//			HttpServletRequest httpServletRequest =
//					((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder
//							.getRequestAttributes()))
//							.getRequest();
			if (!(body instanceof Result)) {
				if (!(body instanceof String)) {
					return Result.success(body);
				} else {
					try {
						return Result.success(body).toJson();
					} catch (Exception exception) {
						log.error("response body to json error", exception);
					}
				}
			}
		}
		return body;
	}
}
